package com.faiz.algorithm;

import java.util.HashMap;
import java.util.Map;

public class LengthOfLongestSubstring {

    // 滑动窗口搞起来
    public int lengthOfLongestSubstring(String s) {
        int l = s.length();
        if (l <= 0) return 0;
        // 初始化
        // window用于记录每一个字下标位置
        Map<Character, Integer> window = new HashMap<>();
        boolean isShrink = false;
        int left = 0, right = 0, res = 0;

        char[] chars = s.toCharArray();
        while (right < l) {
            if (window.containsKey(chars[right])) {
                // 开始缩小窗口
                left = window.get(chars[right]) + 1;
                window.clear();
            }
            window.put(chars[right], right);
            res = Math.max(res, right - left + 1);
            right++;
        }
        return res;
    }

    public static void main(String[] args) {
        String s = "abba";
        LengthOfLongestSubstring lengthOfLongestSubstring = new LengthOfLongestSubstring();
        int i = lengthOfLongestSubstring.lengthOfLongestSubstring(s);
        System.out.println(i);
    }
}
